import { pick } from "lodash-es"
import mitt from "mitt"
import type { PlasmoCSConfig } from "plasmo"

import { sendToBackground } from "@plasmohq/messaging"

import info from "@/test/temporary.json"
import { setDefaultValue } from "@/utils/index"

interface Emitter {
  dom: HTMLElement
  data: any
}

const emitter = mitt<Record<string, Emitter>>()

/**
 * 获取企业信息
 */
export async function handleGetCompanyInfo(e: Event) {
  e.preventDefault()
  e.stopPropagation()

  const panel = document.querySelector(`#${this.dataset.id}`)
  panel.setAttribute("data-loading", "获取企业信息中...")
  panel?.classList.add("activate", "custom-loading")
  this.classList.add("custom-loading")
  // const shopName = panel.previousElementSibling.querySelector(".title--TAzFSB6b")?.textContent
  // const data = JSON.parse(localStorage.getItem("custom_itemsArray") || "[]")
  // const body = data.find((item: any) => item.shopName === shopName)
  // const companyInfo = await sendToBackground({ name: "enterpriseInfo", body })
  // panel.setAttribute("data-loading", "正在通过天眼查获取企业联系方式...")
  // const contactInfo = await sendToBackground({ name: "contactInfo", body: pick(companyInfo, "company_name") })
  // const info = { ...companyInfo, ...contactInfo }
  panel.innerHTML = renderPanel(info)
  this.classList.remove("custom-loading")
  panel?.classList.remove("custom-loading")
  // 注册事件
  emitter.all.forEach((value) => value.forEach((func) => func?.({ dom: panel, data: info })))
}

/**
 * 渲染数据面板
 */
function renderPanel(companyInfo: any) {
  console.log("🚀 ~ hander.ts:31 ~ renderPanel ~ companyInfo:\n", companyInfo)
  const optionHtml = companyInfo.phone_list?.map((item) => `<option value="${item.number}">${item.number}</option>`).join("")
  const cellPhone = companyInfo.phone_list?.find((item) => /1[3-9]\d{9}/g.test(item.number))?.number
  const data = setDefaultValue(companyInfo, "暂无信息")
  const tempStr = data.other_channel?.map((item) => `<span>${item.channel}:${item.phone}</span>`).join("")
  let htmlStr = `
    <li class="item">旺旺：<span style="color: #0063dc;">${data.store_name || "/"}</span></li>
    <li class="item">主营类目：<span>${data.ind || data.main_categories || "/"}</span></li>
    <li class="item">联系电话：<span>${cellPhone || data.phone_list?.at(0)?.number || "/"}</span></li>
    <li class="item">
      <text>公司电话：${optionHtml ? `<select>${optionHtml}</select>` : "<span>/</span>"}</text>
      <strong class="copy-btn">复制</strong>
    </li>
    ${tempStr ? `<li class="item">${tempStr}</li>` : ""}
    <li class="item">企业类型：<span>${data.company_type || "/"}</span></li>
    <li class="item">公司法人：<span>${data.legal_representative || "/"}</span></li>
    <li class="item">信用代码：<span>${data.unified_social_id || "/"}</span></li>
    <li class="item">经营状况：<span style="color: #4777b6;">${data.operating_condition || "/"}</span></li>
    <li class="item">注册资金：<span>${data.registered_capital || "/"}</span></li>
    <li class="item">注册时间：<span>${data.set_up_time || data.registration_date || "/"}</span></li>
    <li class="item">平台状态：<span style="color: #b72f2a;">${data.goods_status ?? "/"}</span></li>
    <li class="item">资质评分：<button class="check-btn" id="check-certification">查看</button></li>
    <li class="item">公司名称：<span>${data.company_name || "/"}</span></li>
    <li class="item col-span-3">公司地址：<span>${data.address || "/"}</span></li>
    <li class="item opening_time">开店时间：<span>${
      isNaN(data.opening_time) ? data.opening_time || "/" : data.opening_time + "年"
    }</span></li>
    <li class="item">天猫入驻：<span>${data.is_tm_enter == 1 ? "是" : "否"}</span></li>
    <li class="item">1688入驻：<span>${data.is_1688_enter == 1 ? "是" : "否"}</span></li>
    <li class="item">京东入驻：<span>${data.is_jd_enter == 1 ? "是" : "否"}</span></li>
  `
  return htmlStr
}

// 查看资质评分
emitter.on("checkCertification", ({ dom, data }) => {
  dom.querySelector("#check-certification")?.addEventListener("click", () => {
    const { uid, shopId } = data
    const url = `https://tbshop.m.taobao.com/app/tb-haodian/h5-pages/impression?sellerId=${uid}&shopId=${shopId}`
    sendToBackground({ name: "certification", body: { url } })
  })
})

// 复制公司电话
emitter.on("copyCompanyTel", ({ data }) => {})

export const config: PlasmoCSConfig = {
  matches: ["https://s.taobao.com/search*"],
  all_frames: true,
  run_at: "document_start",
  world: "MAIN"
}
